package com.myblog.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.common.lang.Result;
import com.myblog.entity.Blog;
import com.myblog.entity.Type;
import com.myblog.service.BlogService;
import com.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author From:星羽恒
 * @since 2021-11-24
 */
@RestController
@RequestMapping("/type")
public class TypeController {
    @Autowired
    TypeService typeService;

    @Autowired
    BlogService blogService;

    @GetMapping("/types")
    public Result getTypeList(){
        //先返回前面几个即可
        List<Type> typeList = (typeService.page(new Page(1,4), new QueryWrapper<Type>().orderByAsc("id"))).getRecords();

        // 返回一个 map ，包含着 每个类别 id ，对应的 blog 数量
        Map<Long,Integer> typeMap = new HashMap<>();
        for(Type tempType : typeList){
            Long typeId = tempType.getId();
            if(!typeMap.containsKey(typeId)){
                int count = blogService.count(new QueryWrapper<Blog>().eq("type_id",typeId));
                typeMap.put(typeId,count);
            }
        }

        return Result.succ(MapUtil.builder()
                            .put("typeList",typeList)
                            .put("typeCountMap",typeMap)
                            .map()
        );
    }

    @GetMapping("/allTypes")
    public Result getAllTypeList(){
        List<Type> typeList = typeService.list();
        Map<Long,Integer> typeMap = new HashMap<>();
        for(Type tempType : typeList){
            Long typeId = tempType.getId();
            if(!typeMap.containsKey(typeId)){
                int count = blogService.count(new QueryWrapper<Blog>().eq("type_id",typeId));
                typeMap.put(typeId,count);
            }
        }

        return Result.succ(MapUtil.builder()
                .put("typeList",typeList)
                .put("typeCountMap",typeMap)
                .map()
        );
    }

}
